﻿using UnityEngine;
using System.Collections;

public class Evasive_Maneuver : MonoBehaviour 
{
    public Rigidbody Enemy;

    public Boundary _Boundary;
    public float tilt;
    public float dodge;
    public float smoothing;
    public Vector2 StartWait;
    public Vector2 ManeuverTime;
    public Vector2 ManeuverWait;

    private float CurrentSpeed;
    private float TargetManeuver;

    void Start()
    {
        CurrentSpeed = Enemy.velocity.z;
        StartCoroutine(Evade());
    }

    IEnumerator Evade ()
    {
        yield return new WaitForSeconds(Random.Range(StartWait.x, StartWait.y));

        while(true)
        {
            TargetManeuver = Random.Range(1, dodge) * -Mathf.Sign(transform.position.x);

            yield return new WaitForSeconds(Random.Range(ManeuverTime.x, ManeuverTime.y));

            TargetManeuver = 0;

            yield return new WaitForSeconds(Random.Range(ManeuverWait.x, ManeuverWait.y));
        }
    }

    void FixedUpdate()
    {
        float newManeuver = Mathf.MoveTowards(Enemy.velocity.x, TargetManeuver, smoothing * Time.deltaTime);

        Enemy.velocity = new Vector3(newManeuver, 0.0f, CurrentSpeed);

        Enemy.position = new Vector3
        (
            Mathf.Clamp(Enemy.position.x, _Boundary.xMin, _Boundary.xMax), 
            0.0f,
            Mathf.Clamp(Enemy.position.z, _Boundary.zMin, _Boundary.zMax)
        );

        Enemy.rotation = Quaternion.Euler(0, 0, Enemy.velocity.x * -tilt);
    }
}
